#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / "scripts"))

def run_all_tests():
    """运行所有测试"""
    
    # 设置测试环境
    import logging
    logging.basicConfig(level=logging.WARNING)
    
    # 创建测试套件
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    
    # 测试文件列表
    test_modules = [
        'tests.test_process_manager',
        'tests.test_dual_service_runner', 
        'tests.test_integration'
    ]
    
    # 加载所有测试
    for module_name in test_modules:
        try:
            module_suite = loader.loadTestsFromName(module_name)
            suite.addTest(module_suite)
            print(f"✓ 已加载测试模块: {module_name}")
        except Exception as e:
            print(f"✗ 加载测试模块失败: {module_name}, 错误: {e}")
    
    # 运行测试
    runner = unittest.TextTestRunner(verbosity=2, buffer=True)
    result = runner.run(suite)
    
    # 输出测试结果摘要
    print("\n" + "="*60)
    print("测试结果摘要")
    print("="*60)
    print(f"运行的测试数量: {result.testsRun}")
    print(f"成功: {result.testsRun - len(result.failures) - len(result.errors)}")
    print(f"失败: {len(result.failures)}")
    print(f"错误: {len(result.errors)}")
    
    if result.failures:
        print("\n失败的测试:")
        for test, traceback in result.failures:
            print(f"  - {test}")
    
    if result.errors:
        print("\n错误的测试:")
        for test, traceback in result.errors:
            print(f"  - {test}")
    
    # 返回是否所有测试都通过
    return len(result.failures) == 0 and len(result.errors) == 0

if __name__ == '__main__':
    print("开始运行 Service Launcher 双服务系统测试...")
    print("="*60)
    
    success = run_all_tests()
    
    if success:
        print("\n🎉 所有测试通过！")
        sys.exit(0)
    else:
        print("\n❌ 部分测试失败，请检查上述错误信息")
        sys.exit(1) 